import {
  USER_INFO,
  TOKEN_KEY,
  IS_LOGIN,
	PASSPORT
} from '@/common/const.js'
import User from '@/model/user.js'

console.log(PASSPORT, USER_INFO)

const state = {
  userInfo: uni.getStorageSync(USER_INFO),
  isLogin: uni.getStorageSync(IS_LOGIN) || false,
  passport: uni.getStorageSync(PASSPORT) || {}
}

const getters = {
  userInfo: state => state.userInfo,
  isLogin: state => state.isLogin,
  passport: state => state.passport
}

const mutations = {
  UPDATE_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
    uni.setStorageSync(USER_INFO, userInfo)
  },
  UPDATE_LOGOUT: (state) => {
    state.userInfo = {}
    state.isLogin = false
    state.passport = {}
    uni.setStorageSync(USER_INFO, {})
    uni.setStorageSync(PASSPORT, {})
    uni.setStorageSync(IS_LOGIN, false)
  },
	UPDATE_PASSPORT: (state, payload) => {
    state.passport = payload
    uni.setStorageSync(PASSPORT, payload)
  },
	UPDATE_IS_LOGIN: (state, payload) => {
    state.isLogin = payload
    uni.setStorageSync(IS_LOGIN, payload)
  },
}

const actions = {
	async login({ commit }, data) {
		const { token } = await User.login(data)
		commit('UPDATE_PASSPORT', token)
		commit('UPDATE_IS_LOGIN', true)
	},
	async codeLogin({ commit }, data) {
		const { token } = await User.codeLogin(data)
		commit('UPDATE_PASSPORT', token)
		commit('UPDATE_IS_LOGIN', true)
	},
	async getUserInfo({ commit }) {
		const result = await User.getMember()
		commit('UPDATE_USER_INFO', result)
	}
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
